#!/bin/bash/python
# _*_ coding: utf-8 _*_
# file： task_upgrade_util
# date-time: 2023/9/14-9:30
# auth:hard work
# description
import sys
import time
import os

from tools_dev_and_sys.tool_ftp_get_put import put_local_file_to_os
from tools_dev_and_sys.tool_ssh_base import SSH_Server

# ip link set eth0 up
# ifconfig mmsa 10.11.1.232 netmask 255.255.255.0
# ifconfig mmsb 10.11.0.232 netmask 255.255.255.0
def base_cfg(device_type):
    if device_type == "gw":
        version_file = "TSN_Release_v{}-usrfs.tar.bz2"
        kernel_file = "nari_v3.fit"
        local_dir = r'C:/version/gw/'
    elif device_type == 'v5':
        version_file = 'kg6524.tar.bz2'
        kernel_file = 'hengshan_v5.fit'
        local_dir = r'C:/version/V5/'


def kernel_auto_upgrade(ip, usrname, passwd, port):
    # _version = input("select version [date]: ")
    _file_name = "nari_v3.fit"
    local_dir = r"C:\\version\\GW\\" + _file_name
    remote_dir = '/app/' + _file_name
    client = SSH_Server(ip, usrname, passwd, port)
    try:
        client.connect()
        client.open_channel()
        if os.path.isfile(local_dir):
            print("found  file ", _file_name)
            client.channel_send_cmd(cmd='cd /app/', break_prompt='# ')
            res = client.channel_send_cmd(cmd='find -name {}'.format(_file_name), break_prompt='# ')
            if "nari_v3.fit" in res:
                print('file is exits ..')
                en_rm_file = input("do you want to remove is: yes|no ")
                if "yes" == en_rm_file:
                    client.channel_send_cmd(cmd='rm -rf {}'.format(_file_name), break_prompt='# ')
                else:
                    rename = input('do you want rename to :')
                    if rename != "":
                        client.channel_send_cmd(cmd='mv {} {}'.format(_file_name, rename), break_prompt='# ')
                    else:
                        print("name is not null, system exit")
                        sys.exit(1)
                    # pass
            else:
                pass

            ret = put_local_file_to_os(client, local_dir, remote_dir, _file_name)
            if ret:
                print("upgrade start ,please wait")
                client.channel_send_cmd(cmd='chmod 755 %s' % _file_name, break_prompt='# ')
                client.channel_send_cmd(cmd='flashcp -v ./%s /dev/mtd0' % _file_name, break_prompt='# ')
                time.sleep(10)
                print("Please reboot to start the new kernel.")
            else:
                print('file not exits')
        else:
            raise "local file not found"

    except FileNotFoundError as e:
        print("local file not found", e)
    except Exception as e:
        print(e)
    else:
        client.close()


def task_auto_upgrade(ip, usrname, passwd, port):
    _version = input("select version: ")
    _file_name = "TSN_Release_v{}-usrfs.tar.bz2".format(_version)
    local_dir = r"C:\\version\\GW\\" + _file_name
    remote_dir = '/app/' + _file_name
    client = SSH_Server(ip, usrname, passwd, port)
    try:
        client.connect()
        client.open_channel()
        if os.path.isfile(local_dir):
            print("found  file ", _file_name)
            client.channel_send_cmd(cmd='cd /app/', break_prompt='# ')
            res = client.channel_send_cmd(cmd='find -name "usrfs*"', break_prompt='# ')
            if 'usrfs' in res:
                en_rm_file = input("do you want to remove it and backup?>>>: yes|no ")
                if "yes" == en_rm_file:
                    client.channel_send_cmd(cmd='telnet 127.0.0.1 2640', break_prompt='> ')
                    client.channel_send_cmd(cmd='enable', break_prompt='# ')
                    client.channel_send_cmd(cmd='write', break_prompt='# ')
                    client.channel_send_cmd(cmd='exit', break_prompt='> ')
                    client.channel_send_cmd(cmd='exit', break_prompt='# ')
                    client.channel_send_cmd(cmd='cd usrfs/cfile/', break_prompt='# ')
                    client.channel_send_cmd(cmd='cp -r ifm ../..', break_prompt='# ')
                    client.channel_send_cmd(cmd='cd /app/usrfs/', break_prompt='# ')
                    client.channel_send_cmd(cmd='./kill_thread.sh', break_prompt='# ')
                    client.channel_send_cmd(cmd='cd ..', break_prompt='# ')
                    client.channel_send_cmd(cmd='rm -rf usrfs*', break_prompt='# ')
                    client.channel_send_cmd(cmd='rm -rf TSN*', break_prompt='# ')
                    # client.channel_send_cmd(cmd='rm -rf usrfs.tar.bz2', break_prompt='# ')

                else:
                    rename = input('do you want rename to :')
                    if rename != "":
                        client.channel_send_cmd(cmd='mv usrfs {}'.format(rename), break_prompt='# ')
                    else:
                        print("name is not null, system exit")
                        sys.exit(1)
                    pass
            else:
                pass

            ret = put_local_file_to_os(client, local_dir, remote_dir, _file_name)
            if ret:
                print("upgrade start ,please wait")
                client.channel_send_cmd(cmd='tar -xjvf %s' % _file_name, break_prompt='# ')
                client.channel_send_cmd(cmd='tar -xjvf usrfs.tar.bz2', break_prompt='# ')
                time.sleep(30)
                res = client.channel_send_cmd(cmd='find -name "usrfs*"', break_prompt='# ')
                if './usrfs' in res:
                    print('auto upgrade success')
                    client.channel_send_cmd(cmd='cp -r ifm usrfs/cfile/', break_prompt='# ')

                    client.channel_send_cmd(cmd='cd usrfs', break_prompt='# ')
                    client.channel_send_cmd(cmd='./gen_bringup.sh kgtsn gw', break_prompt='# ')
                    client.channel_send_cmd(cmd='reboot', break_prompt='# ')
                    print("system is reboot, wait ...")
                    client.close()
                    time.sleep(120)
                    client.connect()
                    client.open_channel()
                    client.channel_send_cmd(cmd='telnet 127.0.0.1 2640', break_prompt='> ')
                    client.channel_send_cmd(cmd='enable', break_prompt='# ')
                    ret = client.channel_send_cmd(cmd='print version', break_prompt='# ')
                    if _file_name == ret:
                        print("current version is :", ret)
                    else:
                        print("error")

                else:
                    print('usrfs file not found')
            else:
                print('file not exits')
        else:
            raise "local file not found"

    except FileNotFoundError as e:
        print("local file not found", e)
    except Exception as e:
        print(e)
    else:
        client.close()


if __name__ == '__main__':

    ip = input("enter dut ip ?>>> ")
    usr_default = input("需要获取一些信息，是否使用默认? yes|no ?>>> ")
    if 'yes' == usr_default:
        usrname = "root"
        passwd = "hengshan"
        port = 22
    else:
        usrname = input("enter dut ssh username ?>>> ")
        passwd = input("enter dut ssh password ?>>> ")
        port = int(input("enter dut ssh port ?>>> "))
    select_model = int(input("upgrade kernel enter 1 \n"
                             "upgrade task enter 2 [1 | 2] ?>>> "))
    if select_model == 1:
        kernel_auto_upgrade(ip, usrname, passwd, port)
    elif select_model == 2:
        task_auto_upgrade(ip, usrname, passwd, port)
    else:
        print("thanks")
        sys.exit(1)
